<template>
  <div class="setting-referrer">
    <div class="hander">
      <button class="btn screen-submit" style="background-color: #999;" @click="addOuterAdviser" v-res="{code:'menu_0004_0001_0007_0002'}">添加外部顾问</button>
      <button class="btn screen-submit" @click="addInnerAdviser" v-res="{code:'menu_0004_0001_0007_0002'}">添加内部顾问</button>
      <button class="btn screen-submit" @click="adviserChange('')" v-res="{code:'menu_0004_0001_0007_0003'}">变更置业顾问</button>
    </div>
    <div class="tableTips">
      <div>
        <img src="../../../assets/images/book.svg" >除变更置业顾问外,
        <font color="red">添加、删除</font>操作均需要点击下方<font color="red">保存设置</font>才会生效
      </div>
      <div>
        <font color="red">内部置业顾问，需先开启报备相关角色权限后，即可以查看其负责接待或跟进的报备数据</font>
      </div>
    </div>
    <div>
      <el-table
          :data="tableData"
          border
          v-loading="loading"
          tooltip-effect="dark"
          style="width: 100%"
          height="320"
          @selection-change="handleSelectionChange">
        <!-- <el-table-column
            type="selection"
            width="55">
        </el-table-column> -->
        <el-table-column
            type="index"
            label="序号"
            width="50">
        </el-table-column>
        <el-table-column
            v-for="item in columns"
            :prop="item.prop"
            :width="item.width"
            :key="item.prop"
            :label="item.label">
        </el-table-column>
        <el-table-column
            label="内部/外部"
            width="120">
          <template slot-scope="scope" >
            {{scope.row.partnerId ? "内部" : "外部"}}
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="120">
          <template slot-scope="scope" >
            <span @click="deleteAdviserModal(scope.row)" style="color: #F87242; cursor: pointer" v-res="{code:'menu_0004_0001_0007_0004'}">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
        title="选择人员"
        ref="chooseDialog"
        width="940px"
        :visible.sync="chooseInnerUserVisible"
        :before-close="chooseUserModalClose">
      <self-dept ref="selfDept" v-if="chooseInnerUserVisible" :user-list="tableData"></self-dept>
      <span slot="footer" class="dialog-footer">
				<button class="btn screen-submit" style="position: static" @click="getSaveData">确认选择</button>
			</span>
    </el-dialog>

  </div>
</template>

<script>
import { Modal } from 'iview'
import SelfDept from './SelfDept.vue'
import {Utils, Service} from '../../../js/base'
export default {
  name: 'AdviserSetting',
  components: {
    SelfDept
  },
  props: {
    loading: {
      type: Boolean,
      default: true
    },
    premisesId: {
      type: String,
      default: null
    },
    adviserList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      tableData: [],
      multipleSelection: [],
      columns: [{
        prop: 'name',
        label: '置业顾问'
      }, {
        prop: 'phone',
        label: '电话'
      }],
      chooseInnerUserVisible: false,
      findPremisesList: []
    }
  },
  mounted () {
  },
  watch: {
    adviserList (val) {
      this.tableData = val
    }
  },
  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    chooseUserModalClose () {
      this.$refs.chooseDialog.$children[0].resetUserItem()
      this.chooseInnerUserVisible = false
    },
    deleteAdviserModal (row) {
      var _this = this;
      let adviserUuid = row.adviserUuid;
      Service.Adviser.getCPCountByAdviser({adviserUuid, _this}).then(response => {
        console.log(response);
        var count = response.resData.count;
        console.log("response.resData = ", response.resData);
        console.log("count = " + count);
        if(count > 0){
          layer.confirm(
            "该置业顾问尚关联有效报备,是否将其变更至新的置业顾问。",
            {
              btn: ["是,去变更", "不,直接删除"]
            },
            function(index) {
              layer.close(index);
              _this.adviserChange(adviserUuid);
            },
            function() {
              _this.tableData = _this.tableData.filter(item => {
                return item.phone !== row.phone
              })
            }
          );
        }else{
          layer.confirm(
            "是否确定删除该置业顾问?",
            {
              btn: ["确定删除", "再考虑考虑"]
            },
            function(index) {
              // 清楚前端数据
              _this.tableData = _this.tableData.filter(item => {
                return item.phone !== row.phone
              });
              layer.close(index);
            },
            function(index) {
            }
          );
        }
      }).catch(e => {
        _this.getAdviserLoading = false
      })
      
    },
    addOuterAdviser () {
      $('#addVisitReview').modal('show')
    },
    addInnerAdviser () {
      this.chooseInnerUserVisible = true
    },
    adviserChange (adviserUuid) {
      this.$parent.originalAdviser = adviserUuid;
      this.$parent.premisesId = this.premisesId
      $('#adviserChangeModal').modal('show')
    },
    getSaveData () {
      const _this = this
      let tableData = JSON.parse(JSON.stringify(_this.tableData))
      this.chooseInnerUserVisible = false
      const userItemList = this.$refs.selfDept.$refs.userItem
      let userInfoList = []
      if (userItemList && userItemList.length) {
        userItemList.forEach(item => {
          if (item.selected && item.userInfo) { // item为vue实例，select是组件实例属性，标记是否选中
            item.userInfo.phone = item.userInfo.phone
            item.userInfo.recommenderId = item.userInfo.id
            item.userInfo.partnerId = item.userInfo.id
            item.userInfo.name = item.userInfo.accountName
            item.userInfo.selected = item.selected
            userInfoList.push(item.userInfo)
          } else if (!item.selected) { // 原有选中，但有此次取消的
            let index = tableData.findIndex(i => i.partnerId && i.phone === item.userInfo.phone)
            if(index > -1) {
              tableData.splice(index, 1)
            }
          }
        })
        let tempList = []
        if (tableData.length) { // 有值去重
          tableData = [...tableData, ...userInfoList]
          let obj = {}, tempKey = ''
          tableData.forEach(item => {
            let index = tempList.findIndex(i => i.phone == item.phone)
            if(index == -1){
              if(!item.partnerId){
                // 非渠道内部用户,直接添加
                tempList.push(item)
              }else{
                tempKey = 'key-' + item.recommenderId;
                if(!obj[tempKey]) {
                  tempList.push(item)
                  obj[tempKey] = true // 标记该值已存在
                }
              }
            }
            
          })
        } else {
          tempList = userInfoList
        }
        this.tableData = [...tempList]
        this.$emit('outerAdviserListener', this.tableData);
      }
    }
  }
}
</script>

<style scoped lang="less">
  .screen-submit {
    position: static;
  }
  .setting-referrer {
    .hander {
      text-align: right;
      .batch-cancel {
        background-color: #fff;
        color: #ccc;
        border: 1px solid;
      }
    }
  }
  .tableTips {float: left; line-height: 20px; color: #333; text-align: left;}
	.tableTips img {width: 20px;height: 20px;margin-bottom: 3px;margin-right: 3px;}
</style>
